package com.ksyun.onepass.service.impl;

import com.ksyun.onepass.service.TradeService;
import com.ksyun.onepass.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Slf4j
@RequiredArgsConstructor
public class TradeServiceImpl implements TradeService {

    // 假设有一个用户服务可以获取用户余额等信息
    private final UserService userService;

    public boolean executeTrade(Long sourceUid, Long targetUid, BigDecimal amount) {
        // 检查用户余额
        BigDecimal sourceBalance = userService.getUserBalance(sourceUid);
        if (sourceBalance.compareTo(amount) < 0) {
            return false; // 源账户余额不足
        }
        BigDecimal sub=sourceBalance.subtract(amount);
        // 执行转账逻辑
        executeTransfer(sourceUid,targetUid,sub,amount);
        return true;
    }
    @Transactional // 确保操作在同一个事务中
    public void executeTransfer(Long sourceUid, Long targetUid, BigDecimal sub,BigDecimal amount) {
        // 扣除源账户金额
        userService.deductAmount(sourceUid,sub);
        // 增加目标账户金额
        userService.addAmount(targetUid, amount);
    }
}
